package com.hp.bon.sgw.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.google.gson.Gson;
import com.hp.bon.sgw.domain.ConvMapInfo;

public class ConvRuleUtil {
	@SuppressWarnings("unchecked")
	private static void exportConvRuleFromXML(String xmlFile)
			throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(xmlFile));
		Element rootEL = document.getRootElement();
		Map<String, StringBuilder> cachedJsonMap = new HashMap<String, StringBuilder>();
		StringBuilder jsonResult = null;
		List<Element> rowEls = rootEL.elements("ROW");
		for (Element rowEL : rowEls) {
			String srvCtxID = rowEL.element("SERVICE_CONTEXT_ID").getText()
					.trim();
			String avpName = rowEL.element("AVP_NAME").getText().trim();
			String avpCode = rowEL.element("AVP_CODE").getText().trim();
			String avpType = rowEL.element("AVP_TYPE").getText().trim();
			String xmlTag = rowEL.element("XML_TAG").getText().trim();
			String venderID = rowEL.element("VENDOR_ID").getText().trim();
			// System.out.println(" row " + srvCtxID);
			ConvMapInfo convMapinf = new ConvMapInfo();
			convMapinf.setServiceCtxID(srvCtxID);
			convMapinf.setAvpName(avpName);
			convMapinf.setAvpCode(Integer.valueOf(avpCode));
			convMapinf.setAvpType(avpType);
			convMapinf.setVenderID(Integer.valueOf(venderID));
			convMapinf.setXmlTag(xmlTag);
			jsonResult = cachedJsonMap.get(srvCtxID);
			if (jsonResult == null) {
				jsonResult = new StringBuilder();
				cachedJsonMap.put(srvCtxID, jsonResult);
			}
			jsonResult.append(new Gson().toJson(convMapinf)).append(',');
//			convMapinf.setDirection(ConvMapInfo.CCA_DIRECTION);
//			jsonResult.append(new Gson().toJson(convMapinf)).append(',');
		}
		jsonResult = new StringBuilder().append('[');
		for (StringBuilder sb : cachedJsonMap.values()) {

			jsonResult.append(sb);
		}
		String totalJson = jsonResult.substring(0, jsonResult.length() - 1);
		totalJson += ']';
		System.out.println("result:" + totalJson);

	}

	public static void main(String[] args) throws DocumentException {
		String convXML = "convertrul.xml";
		exportConvRuleFromXML(convXML);
	}

	
}
